package com.fmr.lead.service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.springframework.stereotype.Service;

import com.fmr.lead.model.TestResult;

@Service
public class ConsoleOutputService {
	public List<TestResult> getTestResults(String job) {
		List<TestResult> logList = new ArrayList<TestResult>();
		TestResult a = new TestResult();
		a.setPid("001");
		a.setSpecName("ForTest1");
		a.getExecutionSteps().add("This is a fake data for testing failed result");
		a.setStatus("Failed");
		a.setExecutionTime("0.0001 seconds");
		
		TestResult b = new TestResult();
		b.setPid("002");
		b.setSpecName("ForTest2");
		b.getExecutionSteps().add("This is a fake data for testing skipped result");
		b.setStatus("Skipped");
		b.setExecutionTime("0.0002 seconds");
		//
		// result.add(t);
		// return result;
		BufferedReader br = null;
		String command = null;

		try {
			command = "curl -D- -k -u " + "a500099" + ":" + "Paper123" + " -X GET "
					+ "https://itec-jenkins.fmr.com/cm2/job/PI/job/Development/job/PR100740/job/AP108513/job/Chart-QA-Regression-Docker/"
					+ job + "/logText/progressiveText?start=0";
			Process p = Runtime.getRuntime().exec(command);
			br = new BufferedReader(new InputStreamReader(p.getInputStream()));
			String line = null;
			while ((line = br.readLine()) != null) {
				if (line.contains("PID")) {
					TestResult t = new TestResult();
					t.setPid(line.substring(18));
					String path = br.readLine().substring(13);
					t.setSpecName(path.substring(path.lastIndexOf("/") + 1, path.length()));
					br.readLine();
					logList.add(t);
					String fine = null;
					while ((fine = br.readLine()) != null && fine.length() != 13) {
						t.getExecutionSteps().add(fine);
					}
					if (Arrays.toString((t.getExecutionSteps().toArray())).contains("error")) {
						continue;
					}
					br.readLine();
					if (br.readLine().contains(" 0 failures")) {
						t.setStatus("Passed");
					} else {
						t.setStatus("Failed");
					}
					t.setExecutionTime(br.readLine().substring(25));
				}
			}

		} catch (

		Exception e) {
			e.printStackTrace();
		} finally {
			if (br != null) {
				try {
					br.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
		logList.add(a);
		logList.add(b);
		return logList;
	}
}
